//const { User, Role, Coupon, Article, sequelize, Department, UserDepartmentRole, UserCoupon } = require('./models');
const WxPay = require('wechatpay-node-v3');

const dayjs = require("dayjs");
const { rand } = require('./helpers/function');
const fs = require('fs');
const path = require('path');

(async () => {
	const { weapp: { app_id: appid }, wxpay: { mch_id: mchid, key, public_key: publicKey, private_key: privateKey } } = require("./config/config");

	//退款
	const wxpay = new WxPay({
		appid,
		mchid,
		publicKey,
		privateKey,
	});

	const raw = '{"id":"df89a7e5-b774-5c58-b81c-da060c9ec541","create_time":"2024-03-22T18:13:41+08:00","resource_type":"encrypt-resource","event_type":"REFUND.SUCCESS","summary":"退款成功","resource":{"original_type":"refund","algorithm":"AEAD_AES_256_GCM","ciphertext":"2o19h5q0gOL/TsGP3/b8ujubkKEfgjACMs1K0bTW8T5KFus17RNvjnRaCIRXoAfn+PQbOodtqfkSrCGQBxqNoKBIbjPcIhLRPb/Yllpd2YSFf4gtEBL2NdXW5KNJv4IVs4ntUyhuMBIIYNnfXwW+1HB9J4oHLX4+sriQ3hFnXBnXtQOYa0VmeAqBUiKO4Htiui8fBjDY7c/ujTEZstbucNzWANoT7Y2dCAJtg5NxNifnxFWXkzZ/BgziavBDqtrJI0/OiHBF6dGZ9rmAcdfNKKpkOYWEfkno/JXKbdpYonHW1bfReKm8JvXD8D/KMD06LP7mhQ3Srws3GJ4Ajuney3YXn0pe7rgJFZjyx/pNeScesSEWkqCotyMhmRikkynMjWdqkLo3OdI6v0EEvip3Itk564f1U7CcnpitCpCKaBXCtVYp9RZAmXiQvpxVbrnOYnEtSTLTQgzoMObZwd73bN1wL9RpS76MesqgPRT+h55dGR9enLr/kwUDBU9/fQ==","associated_data":"refund","nonce":"sNrXfNApdPe0"}}';
	const data = JSON.parse(raw);
	const {
		ciphertext,
		associated_data,
		nonce
	} = data.resource;
	// 解密回调信息
	const {
		refund_status,
		out_trade_no,
		out_refund_no,
		amount
	} = wxpay.decipher_gcm(ciphertext, associated_data, nonce, key);
	console.log({
		refund_status,
		out_trade_no,
		out_refund_no,
		amount
	});
	return;

	const result = await wxpay.refunds({
		out_trade_no: '202403221759573761',
		out_refund_no: `${dayjs().format('YYYYMMDDHHmmss')}${rand(1000, 9999)}`,
		notify_url: 'https://mp.kachewo.com/api/wxpay/callback/refund/notify',
		amount: {
			refund: 1,
			total: 1,
			currency: 'CNY'
		}
	});
	console.log(result);

	return;

	User.findByPk(1, {
		//include: ["roles"],

		include: {
			model: Role,
			as: 'roles',
			attributes: ['name'],

			through: {
				attributes: []
			}
		}
	}, {
		attributes: {
			exclude: ['password']
		}
	}).then(async (data) => {
		console.log(JSON.stringify(data.toJSON()));

		//新增角色
		/*
		const role = await Role.findByPk(2);
		data.addRole(role, {
			through: {
				department_id: 0
			}
		});
		*/
	});
})();

return;

(async () => {
	//创建表，若表已存在则忽略
	//sequelize.sync();
	await sequelize.sync({ force: false });

	//强制重建表，如果表已存在，则先删除
	//sequelize.sync({ force: true });

	//检查表的当前状态，如果与模型不一致，则修改表结构与模型一致。
	//sequelize.sync({ alter: true });

	//sequelize.models.Role => sequelize.define('Role'
	console.log(Role === sequelize.models.Role);

	//创建用户
	//const user = await User.create({ username: 'njroye' });

	//const department = await Department.create({ name: '市场部' });
	//const department = await Department.findOne({ where: { id: 1 } });

	//await user.addDepartment(department, { through: { role_id: 0 } });

	//await user.addDepartments([department]);

	//await user.setDepartment(department);


	//创建用户并发券
	/*
	const user = await User.create({ username: 'njroye' });
	const coupon = await Coupon.findByPk(1);
	//const coupon = await Coupon.create({ name: '优惠券' });
	*/

	/*
	//1
	await user.addCoupon(coupon, { through: { status: 1 } });

	//2
	user.setCoupons([coupon], { through: { status: 1 } });

	//3 The default status value is 1, but coupon1 overrides that.
	const coupon1 = await Coupon.findByPk(1);
	//sequelize.define('UserCoupon'
	coupon1.UserCoupon = {
		status: 3
	}
	const coupon2 = await Coupon.findByPk(2);
	user.setCoupons([coupon1, coupon2], { through: { status: 1 } });
	*/


	/*
	const user = User.build({ username: 'build' });
	user.gender = 1;

	user.set({
		phone: '13813811845'
	});
	//save保存所有修改的字段（gender和phone）
	await user.save();

	//update只更改指定字段（phone）
	await user.update({
		phone: '18021504988'
	});
	*/

	/*
	const user = await User.findByPk(86);
	user.username = 'idc';
	console.log(user.toJSON()); //username: idc

	await user.reload();
	console.log(user.toJSON()); //username: njroye

	//仅保存部分字段
	user.username = 'idc';
	user.gender = 2;
	//数据库中只更新了username字段
	await user.save({ fields: ['username'] });
	console.log(user.toJSON());
	*/

	/*
	const article = await Article.findByPk(1);
	await article.increment('pv', { by: 2 });
	await article.increment({
		pv: 2,
		sort: 2
	});
	await article.increment(['pv', 'sort'], { by: 2 });
	*/

	/*
	//只能保存username字段
	await User.create({
		username: 'username',
		gender: 2
	}, {
		fields: ['username']
	});
	*/

	/*
	const article = await Article.findOne({
		where: {
			id: 1
		},
		attributes: [
			'id', 'title',
			//['images', 'thumb'],
			[sequelize.fn('substring_index', sequelize.col('images'), ',', 1), 'thumb'],
			[sequelize.fn('unix_timestamp', sequelize.col('create_time')), 'create_time'],
		]
	});
	console.log(article.toJSON());
	*/

	/*
	//删除
	const user = await User.findByPk(86);
	const coupons = await user.getCoupons();
	//user.removeCoupons(coupons);
	await user.setCoupons([]);
	*/

	/*
	const user = await User.findOne({
		where: {
			id: 1
		},

		//belongsToMany
		include: [{
			model: Department,
			as: 'departments'
		}],

		//必须先设置User.hasMany(UserDepartmentRole，否则报错
		include: {
			model: UserDepartmentRole,

			//UserDepartmentRole.belongsTo(Department、UserDepartmentRole.belongsTo(Role
			include: [{
				model: Department,
				attributes: ['name']
			}, {
				model: Role,
				attributes: ['name']
			}],
		}
	});

	const { UserDepartmentRoles } = user.toJSON();
	console.log(UserDepartmentRoles);
	*/

	/*
	const user = await User.findByPk(1);

	const coupon1 = await Coupon.create({ name: '100元抵扣券' });
	const coupon2 = await Coupon.create({ name: '500元抵扣券' });
	const coupon1 = await Coupon.findByPk(11);
	const coupon2 = await Coupon.findByPk(12);


	//set：不在传递的数组中的所有内容都将取消关联，如果传空，则表示取消（删除）所有关联
	//await user.setCoupons([]);
	//await user.setCoupons([coupon1, coupon2]);

	//add：不在传递数组中的内容不会取消关联
	await user.addCoupons([coupon2]);
	*/

	/*
	await User.create({
		username: 'njroyey',

		//sequelize.define('Coupon'
		//Coupons: [{ name: '优惠券xx' }]

		//as: 'coupons'
		coupons: [{
			name: '优惠券xx'
		}]
	}, {
		include: [
			//User.Coupon =
			//{ association: User.Coupon },

			//Coupon,

			//as: 'coupons'
			'coupons'
		]
	});
	*/

	/*
	const user = await User.create({
		username: 'njroyeabc',

		//as: 'coupons'
		coupons: [{
			name: '优惠券abc',

			UserCoupon: {
				status: 1
			}
		}]
	}, {
		include: 'coupons'
	});
	*/

	/*
	const user = await User.findByPk(50, { include: 'coupons' });
	const user = await User.findByPk(50, {
		include: {
			model: Coupon,
			as: 'coupons',
			through: {
				attributes: []
			}
		}
	});
	*/

	/*
	const user = await User.findByPk(50);
	const coupons = await user.getCoupons();

	//coupons.JSON()会报错，因为coupons是个数组，只有数组内的Coupon对象实例才可以toJSON()
	console.log(coupons);


	//只需要UserCoupon中的status
	const coupons = await user.getCoupons({ joinTableAttributes: ['status'] });
	coupons.map((d) => {
		console.log(d.toJSON());
	})
	*/


	/*
	//方案一
	const user = await User.findOne({
		include: {
			model: UserDepartment,

			include: [
				Department,
				{
					model: Role,
					attributes: ['id', 'name'],
					through: { attributes: [] }
				}
			]
		}
	});
	const data = user.toJSON();
	console.log(data, data.UserDepartments[0].Department, data.UserDepartments[0].Roles);
	*/

	//方案二
	const user = await User.findOne({
		where: { id: 1 },
		//include: [Department, Role],

		/*
		include: {
			model: Role,
			through: {
				attributes: ['department_id']
			}
		}
		*/

		include: {
			model: UserDepartmentRole,
			include: [Department, Role]
		}
	});
	console.log(user.toJSON());

	console.log('success');
})();
